import { ConfigProvider, message, theme } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import dayjs from 'dayjs';
import { history } from 'umi';

import { WMDiv } from '@/components/base';
import { ErrorBoundary } from '@/layouts/components/ErrorBoundary';
import request from '@/utils/request';

import 'dayjs/locale/zh-cn';

import defaultSettings from '../config/defaultSettings';
import { homeUrl } from '../config/routes';
import { redirectList } from '../config/routes/redirect';

import { storage } from './utils/storage';
import { APP_LOGO } from './appConfig';
dayjs.locale('zh-cn');

import {
  headerContentRender,
  headerRightContentRender,
} from './layouts/components/Header/ProductNavigator';

export const antd = (memo) => {
  memo.theme.algorithm = theme.compactAlgorithm;
  return memo;
};

const loginPath = '/login';
const landingPath = '/landing';
const devTestUser = {
  avatar: '/avatar.jpg',
  name: 'user01',
  display: '测试用户-测试部门',
};

function isProduction() {
  return process.env.NODE_ENV === 'production';
}

export async function getInitialState() {
  const fetchUserInfo = async () => {
    const userEmail = storage.getItem('user');
    const { location } = history; // 如果没有登录，重定向到 login
    const { pathname } = location;
    const resp = await request(`/api/current_user`, {
      params: {
        email: userEmail,
      },
    });

    if (!resp.success && pathname !== loginPath && pathname !== landingPath) {
      window.location.replace(landingPath);
      message.info(resp.msg);
      return;
    }
    if (resp.success) {
      return resp.data;
    }

    if (isProduction()) {
      history.push(loginPath);
      return undefined;
    }

    if (history.location.query['MOCK_USER'] === '1') {
      return devTestUser;
    }
  };

  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
    };
  }

  return {
    fetchUserInfo,
  };
}

export function onRouteChange({ location }) {
  const { pathname } = location;
  if (pathname === '/') {
    history.push(homeUrl);
  }
  const dirPath = redirectList.find(
    (item) =>
      item.path === location.pathname || item.path + '/' === location.pathname,
  );
  if (dirPath) {
    history.replace(`${dirPath.redirect}${location.search}`);
  }
}

export const layout = ({ initialState }) => {
  const onPageChange = () => {
    const { location } = history; // 如果没有登录，重定向到 login
    const { pathname } = location;
    if (
      !initialState.currentUser &&
      pathname !== loginPath &&
      pathname !== landingPath
    ) {
      history.push(landingPath);
      return;
    }
  };

  const childrenRender = (children) => {
    if (initialState?.loading) return <div />;
    return (
      <ConfigProvider locale={zhCN}>
        <ErrorBoundary>
          <div style={{ margin: '0 100px' }}>{children}</div>
        </ErrorBoundary>
        <WMDiv />
      </ConfigProvider>
    );
  };
  return {
    ...defaultSettings,
    logo: APP_LOGO,
    token: {
      header: {
        headerBgColor: 'white',
        heightLayoutHeader: 42,
      },
      pageContainer: {
        pageContainerBgColor: '#f8f9fa',
        pageContainerFixedBgColor: '#f8f9fa',
        paddingInlinePageContainerContent: 0,
        paddingBlockPageContainerContent: 0,
      },
      borderColorSplit: '#dadce0',
    },
    breadcrumbRender: false,
    ErrorBoundary: ErrorBoundary,
    onMenuHeaderClick: () => {
      history.push(homeUrl);
    },
    headerContentRender,
    rightContentRender: headerRightContentRender,
    childrenRender,
    onPageChange,
  };
};
